import React, { Component, useRef } from 'react';
import { Input, message, Select } from 'antd';
import useProjectData from 'src/hook/useProjectData';
import CustomForm from '../../../../components/CustomForm';
import services from '../../../../services/api';

const SortAdd = (props) => {
  const { actionType, closeModal, freshQueryList } = props;
  const form = useRef(null);
  const api = 'sort';
  const projectList = useProjectData();

  const handleSubmit = () => {
    form.current.validateFields((err, values) => {
      if (!err) {
        const { name, code, remark, projectCode } = values;
        const params = {
          name,
          code,
          remark,
          projectCode,
        };
        services[api][actionType](params).then((data) => {
          if (data.code === '0') {
            message.success(data.msg);
            closeModal && closeModal();
            freshQueryList && freshQueryList();
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  const formItems = [
    {
      label: {
        label: '项目',
      },
      name: 'projectCode',
      options: {
        initialValue: undefined,
        rules: [{ required: true, message: '请选择项目' }],
      },
      component: (
        <Select placeholder='请选择' allowClear>
          {projectList.map((it) => {
            return (
              <Select.Option value={it.code} key={it.code}>
                {it.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '分类名称',
      },
      name: 'name',
      options: {
        initialValue: '',
        rules: [{ required: true, message: '请输入分类名称' }],
      },
      component: <Input placeholder='请输入' disabled={actionType === 'detail'} />,
    },
    {
      label: {
        label: '分类code',
      },
      name: 'code',
      options: {
        initialValue: '',
        rules: [
          { required: true, message: '请输入分类code' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
        ],
      },
      component: <Input placeholder='请输入' disabled={actionType === 'update' || actionType === 'detail'} />,
    },
    // {
    //   label: {
    //     label: '描述',
    //   },
    //   name: 'remark',
    //   options: {
    //     initialValue: '',
    //     rules: [{ max: 256, message: '最长256个字符' }],
    //   },
    //   component: <Input.TextArea placeholder='请输入' />,
    // },
  ].filter(Boolean);

  return (
    <CustomForm
      {...props}
      createForm={(ref) => (form.current = ref)}
      formItems={formItems}
      onHandleSubmit={handleSubmit}
      colNum={1}
      hideSubmit={actionType === 'detail'}
    />
  );
};

export default SortAdd;
